<template>
  <div class="container">
    <!-- 上半部分内容 -->
    <div class="content-wrapper">
      <div class="sidebar">
        <div v-for="item in items" :key="item.name" class="item" @click="selectedItem = item">
          <div class="sidebar-item" style="display: flex; flex-direction: column; height: 100%" @click="addToFileList(item)">
            <div class="hover-byover">
              <div style="display: flex; flex: 1; justify-content: center; align-items: center">{{ item.name }}</div>
              <div style="display: flex; flex: 1; justify-content: center; align-items: center">{{ item.score }} 份</div>
            </div>
            <div class="hover-over"> 点击加入></div>
          </div>
        </div>
      </div>
      <div class="main-content">
        <div v-if="fileList.length === 0" class="new-material">
          <div style="border: 1px dashed #ccc; padding: 20px; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column">
            <h2>新建材料</h2>
            <p>请从左侧选择成果类别点击按钮进入框架</p>
          </div>
        </div>
        <div v-else class="file-filter" style="width: 100%; height: calc(100% - 50px); overflow-y: auto">
          <div style="display: flex; position: absolute; top: 0; height: 45px; width: 100%;">
            <div style="flex: 1; padding: 10px; font-weight: bold; font-size: 16px;"> 材料筛选器</div>
            <div style="flex: 1"></div>
          </div>
          <el-collapse v-model="activeNames" style="margin-top: 45px">
            <el-collapse-item style="padding: 0 20px" v-for="(item, index) in fileList" :title="(index+1) + '：' + item.name + '（' + item.score + '篇）'" :name="index" :key="index">
              <div v-if="item.name === '档案资料'">
                <el-table size="small" :data="certificationList" border style="width: 100%" @selection-change="handleCertificationSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="createdAt" label="获奖时间" width="180" />
                  <el-table-column prop="certificateType" label="证书类型" />
                </el-table>
              </div>
              <div v-if="item.name === '继续教育材料'">
                <el-table size="small" :data="continueEducationList" border style="width: 100%" @selection-change="handleContinueEducationSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="hours" label="课时" width="180" />
                  <el-table-column prop="createdAt" label="获奖时间" width="180" />
                  <el-table-column prop="trainingUnit" label="培训单位" />
                </el-table>
              </div>
              <div v-if="item.name === '软件著作权'">
                <el-table size="small" :data="softwareCopyrightList" border style="width: 100%" @selection-change="handleSoftwareCopyrightSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="created" label="获奖时间" width="180" />
                  <el-table-column prop="copyrightType" label="著作权类型" width="180" />
                  <el-table-column prop="copyrightOwner" label="著作权人" />
                </el-table>
              </div>
              <div v-if="item.name === '横向课题'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="HorizontalList" border @selection-change="handleHorizontalSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="projectName" label="标题" width="180" />
                  <el-table-column prop="contractSource" label="合同来源" width="180" />
                  <el-table-column prop="fundingAmount" label="到账经费(万)" width="180" />
                  <el-table-column prop="projectStatus" label="课题状态" width="180" />
                  <el-table-column prop="startTime" label="开始时间" width="180" />
                  <el-table-column prop="rank" label="本人排名" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '纵向课题'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="LongitudinalList" border @selection-change="handleLongitudinalSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="projectName" label="标题" width="180" />
                  <el-table-column prop="fundName" label="基金名称" width="180" />
                  <el-table-column prop="projectLevel" label="课题级别" width="180" />
                  <el-table-column prop="fundingAmount" label="到账经费(万)" width="180" />
                  <el-table-column prop="projectStatus" label="课题状态" width="180" />
                  <el-table-column prop="startTime" label="开始时间" width="180" />
                  <el-table-column prop="rank" label="本人排名" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '其他'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="otherList" border @selection-change="handleOtherSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="authorRank" label="本人排名" width="180" />
                  <el-table-column prop="createdAt" label="获得时间" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '论文'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="paperList" border @selection-change="handlePaperSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="journalName" label="刊物名称" width="180" />
                  <el-table-column prop="indexing" label="收录检索" width="180" />
                  <el-table-column prop="impactFactor" label="影响因子" width="180" />
                  <el-table-column prop="publishDate" label="发表时间" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '专利'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="patentList" border @selection-change="handlePatentSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="patentType" label="专利类型" width="180" />
                  <el-table-column prop="patentNumber" label="专利编号" width="180" />
                  <el-table-column prop="authorizationDate" label="授权公告日" width="180" />
                  <el-table-column prop="patentStatus" label="专利状态" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '个人获奖'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="personalAwardList" border @selection-change="handlePersonalAwardSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="awardLevel" label="获奖名次" width="180" />
                  <el-table-column prop="level" label="级别" width="180" />
                  <el-table-column prop="grantingUnit" label="授予单位" width="180" />
                  <el-table-column prop="awardTime" label="获奖时间" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '著作'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="publicationList" border @selection-change="handlePublicationSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="publisher" label="出版社" width="180" />
                  <el-table-column prop="isbn" label="出版号" width="180" />
                  <el-table-column prop="wordCount" label="字数(千字)" width="180" />
                  <el-table-column prop="publishDate" label="出版时间" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '新闻报道'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="reportList" border @selection-change="handleReportSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="mediaLevel" label="媒体级别" width="180" />
                  <el-table-column prop="reportTime" label="报道时间" width="180" />
                </el-table>
              </div>
              <div v-if="item.name === '学生奖项'">
                <el-table style="width: 100%" maxHeight="250" size="small" :data="studentAwardList" border @selection-change="handleStudentAwardSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="number" label="序号" width="180" />
                  <el-table-column prop="title" label="标题" width="180" />
                  <el-table-column prop="awardLevel" label="获奖名次" width="180" />
                  <el-table-column prop="level" label="级别" width="180" />
                  <el-table-column prop="grantingUnit" label="授予单位" width="180" />
                  <el-table-column prop="awardTime" label="获奖时间" width="180" />
                  <el-table-column prop="awardStudents" label="获奖学生" width="180" />
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <div class="footer">
          <button style="background-color: #00B38A; color: white; border-radius: 0; padding: 0.4em 1em; font-size: 14px; cursor: pointer" @click="nextStep">下一步</button>
        </div>
      </div>
    </div>


    <div class="history-section">
      <h2 class="history-title">材料历史记录</h2>
      <div class="history-table-container">
        <table class="history-table">
          <thead>
          <tr>
            <th>文件名</th>
            <th>状态</th>
            <th>生成时间</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="record in historyRecords" :key="record.id">
            <td>{{ record.title }}</td>
            <td>
                <span class="status">
                  <span class="status-dot completed"></span>
                  已完成
                </span>
            </td>
            <td>{{ formatDate(record.creationTime, 'yyyy-MM-dd') }}</td>
            <td class="actions">
              <a @click="handleDownload(record)">
                <i class="el-icon-download"></i>
                下载
              </a>

              <el-dropdown trigger="click" @command="(command) => handleCommand(command, record)">
                <a>
                  <i class="el-icon-more"></i>
                  更多
                </a>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                    <el-dropdown-item command="rename">重命名</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </td>
          </tr>
          </tbody>
        </table>

        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import { CertificationAward } from '@/api/Manage/Certification';
import { getContinueEducation } from "@/api/Manage/ContinueEducation";
import { getCopyRight } from "@/api/Manage/software"
import { getHorizontalsList } from "@/api/Research/Horizontal"
import { getLongitudinalList } from "@/api/Research/Longitudinal"
import { getOtherMessage } from "@/api/Manage/Other"
import { paperApi } from "@/api/Manage/Paper"
import { getPatent } from "@/api/Manage/Patent"
import { getPersonalAward } from "@/api/Manage/PersonalAward"
import { getPublication } from "@/api/Manage/Publication"
import { getReport } from "@/api/Manage/Report"
import { getStudentAward } from "@/api/Manage/StudentAward"
import { useRouter } from "vue-router";
import { listMaterialHistory,deleteMaterialHistory,updateMaterialHistoryTitle } from '@/api/Assistants/material.js';

// 添加历史记录相关的变量
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const historyRecords = ref([]);

const router = useRouter();
const activeNames = ref(['1'])
const fileList = ref([]);
const items = ref([
  { name: '论文', score: 0 },
  { name: '纵向课题', score: 0 },
  { name: '专利', score: 0 },
  { name: '学生奖项', score: 0 },
  { name: '软件著作权', score: 0 },
  { name: '个人获奖', score: 0 },
  { name: '继续教育材料', score: 0 },
  { name: '著作', score: 0 },
  { name: '横向课题', score: 0 },
  { name: '新闻报道', score: 0 },
  { name: '档案资料', score: 0 },
  { name: '其他', score: 0 },
]);

const nextStep = () => {
  if (fileList.value.length === 0) {
    ElMessage({
      message: '请先从左侧选择至少一个材料类型添加到筛选区',
      type: 'warning',
    })
    return;
  }

  // 收集所有选中的材料信息
  const selectedMaterials = [];
  const missingPdfItems = [];

  for (const item of fileList.value) {
    const name = item.name;
    let selectedItems = [];

    // 根据不同的材料类型获取选中的项目
    if (name === '档案资料') {
      selectedItems = certificationList.value.filter((cert) => cert.selected);
    } else if (name === '继续教育材料') {
      selectedItems = continueEducationList.value.filter((edu) => edu.selected);
    } else if (name === '软件著作权') {
      selectedItems = softwareCopyrightList.value.filter((copy) => copy.selected);
    } else if (name === '横向课题') {
      selectedItems = HorizontalList.value.filter((h) => h.selected);
    } else if (name === '纵向课题') {
      selectedItems = LongitudinalList.value.filter((l) => l.selected);
    } else if (name === '其他') {
      selectedItems = otherList.value.filter((o) => o.selected);
    } else if (name === '论文') {
      selectedItems = paperList.value.filter((p) => p.selected);
    } else if (name === '专利') {
      selectedItems = patentList.value.filter((p) => p.selected);
    } else if (name === '个人获奖') {
      selectedItems = personalAwardList.value.filter((a) => a.selected);
    } else if (name === '著作') {
      selectedItems = publicationList.value.filter((p) => p.selected);
    } else if (name === '新闻报道') {
      selectedItems = reportList.value.filter((r) => r.selected);
    } else if (name === '学生奖项') {
      selectedItems = studentAwardList.value.filter((a) => a.selected);
    }

    // 将选中的项目添加到结果中，并检查PDF路径
    for (const selectedItem of selectedItems) {
      const pdfPath = selectedItem.pdfPath || selectedItem.pdfUrl;
      const title = selectedItem.title || selectedItem.projectName || selectedItem.name;

      // 检查是否有PDF路径
      if (!pdfPath || pdfPath === '/placeholder.pdf') {
        missingPdfItems.push({
          type: name,
          title: title
        });
      }

      selectedMaterials.push({
        type: name,
        title: title,
        pdfUrl: pdfPath || '/placeholder.pdf' // 确保有PDF路径
      });
    }
  }

  // 如果没有选中任何具体项目
  if (selectedMaterials.length === 0) {
    ElMessage({
      message: '请在材料筛选区中选择具体的项目',
      type: 'warning',
    });
    return;
  }

  // 如果有项目缺少PDF文件

  if (missingPdfItems.length > 0) {
    let missingItemsText = missingPdfItems.map(item => `${item.type}: ${item.title}`).join('\n');

    ElMessage({
      type: 'warning',
      message: `以下材料缺少PDF文件，请先上传文件后再继续：\n${missingItemsText}`,
      duration: 5000, // 5秒后自动消失
      showClose: true // 允许手动关闭
    });

  } else {
    // 所有项目都有PDF文件，直接进行下一步
    proceedToNextStep(selectedMaterials);
  }

};

// 提取进入下一步的逻辑为单独的函数
const proceedToNextStep = (selectedMaterials) => {
  console.log('进入下一步：', selectedMaterials);
  router.push({
    path: '/academic/material',
    query: {
      projectName: '材料合集',
      projectLevel: '',
      projectNumber: '',
      startTime: formatDate(Date.now(), 'yyyy-MM-dd'),
      projectStatus: '进行中',
      results: JSON.stringify(selectedMaterials)
    }
  });
};

const selectedItem = ref(null);

function formatDate(timestamp, format) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  format = format.replace('yyyy', year.toString());
  format = format.replace('MM', month < 10 ? '0' + month : month.toString());
  format = format.replace('dd', day < 10 ? '0' + day : day.toString());
  format = format.replace('HH', hours < 10 ? '0' + hours : hours.toString());
  format = format.replace('mm', minutes < 10 ? '0' + minutes : minutes.toString());
  format = format.replace('ss', seconds < 10 ? '0' + seconds : seconds.toString());

  return format;
}

const addToFileList = (item) => {
  // 检查是否已经存在于 fileList 中
  const isExist = fileList.value.some((file) => file.name === item.name);

  if (isExist) {
    ElMessage({
      message: `${item.name} 已经添加到材料筛选区，不能重复添加！`,
      type: 'warning',
    });
    return;
  }

  // 如果不存在，则添加到 fileList
  fileList.value.push(item);
};

const params = reactive({
  isAsc: true,
  pageNo: 1,
  pageSize: 10000,
  sortBy: 'id',
  startDate: "",
  endDate: "",
  total: 0
});

// 生成材料页数据初始化加载
const certificationList = ref([]);
const initCertificationData = async () => {
  const certificationRes = await CertificationAward(params);
  certificationList.value = certificationRes.data.list;
  let number = 1;
  certificationList.value.forEach((item) => {
    item.number = number++;
    item.createdAt = formatDate(item.createdAt, 'yyyy-MM-dd HH:mm:ss');
    item.updatedAt = formatDate(item.updatedAt, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[10].score = certificationList.value.length;
}

// 继续教育材料数据初始化加载
const continueEducationList = ref([]);
const initContinueEducationData = async () => {
  const continueEducationRes = await getContinueEducation(params);
  continueEducationList.value = continueEducationRes.data.list;
  let number = 1;
  continueEducationList.value.forEach((item) => {
    item.number = number++;
    item.createdAt = formatDate(item.createdAt, 'yyyy-MM-dd HH:mm:ss');
    item.updatedAt = formatDate(item.updatedAt, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[6].score = continueEducationList.value.length;
}

// 软件著作权数据初始化加载
const softwareCopyrightList = ref([]);
const initSoftwareCopyrightData = async () => {
  const softwareCopyrightRes = await getCopyRight(params);
  softwareCopyrightList.value = softwareCopyrightRes.data.list;
  let number = 1;
  softwareCopyrightList.value.forEach((item) => {
    item.number = number++;
    item.created = formatDate(item.created, 'yyyy-MM-dd HH:mm:ss');
    item.created = formatDate(item.created, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[4].score = softwareCopyrightList.value.length;
}

// 横向课题数据初始化加载
const HorizontalList = ref([]);
const initHorizontalData = async () => {
  const HorizontalRes = await getHorizontalsList(params);
  HorizontalList.value = HorizontalRes.data.list;
  let number = 1;
  HorizontalList.value.forEach((item) => {
    item.number = number++;
    item.startTime = formatDate(item.startTime, 'yyyy-MM-dd HH:mm:ss');
    item.updatedAt = formatDate(item.updatedAt, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[8].score = HorizontalList.value.length;
}

// 纵向课题数据初始化加载
const LongitudinalList = ref([]);
const initLongitudinalData = async () => {
  const LongitudinalRes = await getLongitudinalList(params);
  LongitudinalList.value = LongitudinalRes.data.list;
  let number = 1;
  LongitudinalList.value.forEach((item) => {
    item.number = number++;
    item.startTime = formatDate(item.startTime, 'yyyy-MM-dd HH:mm:ss');
    item.updatedAt = formatDate(item.updatedAt, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[1].score = LongitudinalList.value.length;
}

// 其他数据初始化加载
const otherList = ref([]);
const initOtherData = async () => {
  const otherRes = await getOtherMessage(params);
  otherList.value = otherRes.data.list;
  let number = 1;
  otherList.value.forEach((item) => {
    item.number = number++;
    item.createdAt = formatDate(item.createdAt, 'yyyy-MM-dd HH:mm:ss');
    item.updatedAt = formatDate(item.updatedAt, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[11].score = otherList.value.length;
}

// 论文数据初始化
const paperList = ref([]);
const initPaperData = async () => {
  const paperRes = await paperApi.getPapers(params);
  paperList.value = paperRes.data.list;
  let number = 1;
  paperList.value.forEach((item) => {
    item.number = number++;
    item.publishDate = formatDate(item.publishDate, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[0].score = paperList.value.length;
}

// 专利数据初始化
const patentList = ref([]);
const initPatentData = async () => {
  const patentRes = await getPatent(params);
  patentList.value = patentRes.data.list;
  let number = 1;
  patentList.value.forEach((item) => {
    item.number = number++;
    item.authorizationDate = formatDate(item.authorizationDate, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[2].score = patentList.value.length;
}

// 个人获奖数据初始化
const personalAwardList = ref([]);
const initPersonalAwardData = async () => {
  const personalAwardRes = await getPersonalAward(params);
  personalAwardList.value = personalAwardRes.data.list;
  let number = 1;
  personalAwardList.value.forEach((item) => {
    item.number = number++;
    item.awardTime = formatDate(item.awardTime, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[5].score = personalAwardList.value.length;
}

// 著作数据初始化
const publicationList = ref([]);
const initPublicationData = async () => {
  const publicationRes = await getPublication(params);
  publicationList.value = publicationRes.data.list;
  let number = 1;
  publicationList.value.forEach((item) => {
    item.number = number++;
    item.publishDate = formatDate(item.publishDate, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[7].score = publicationList.value.length;
}

// 新闻报道数据初始化
const reportList = ref([]);
const initReportData = async () => {
  const reportRes = await getReport(params);
  reportList.value = reportRes.data.list;
  let number = 1;
  reportList.value.forEach((item) => {
    item.number = number++;
    item.reportTime = formatDate(item.reportTime, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[9].score = reportList.value.length;
}

//学生获奖数据初始化
const studentAwardList = ref([]);
const initStudentAwardData = async () => {
  const studentAwardRes = await getStudentAward(params);
  studentAwardList.value = studentAwardRes.data.list;
  let number = 1;
  studentAwardList.value.forEach((item) => {
    item.number = number++;
    item.awardTime = formatDate(item.awardTime, 'yyyy-MM-dd HH:mm:ss');
    item.selected = false;
  });
  items.value[3].score = studentAwardList.value.length;
}

// 选择变更处理函数
const handleCertificationSelectionChange = (selection) => {
  certificationList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleContinueEducationSelectionChange = (selection) => {
  continueEducationList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleSoftwareCopyrightSelectionChange = (selection) => {
  softwareCopyrightList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleHorizontalSelectionChange = (selection) => {
  HorizontalList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleLongitudinalSelectionChange = (selection) => {
  LongitudinalList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleOtherSelectionChange = (selection) => {
  otherList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handlePaperSelectionChange = (selection) => {
  paperList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handlePatentSelectionChange = (selection) => {
  patentList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handlePersonalAwardSelectionChange = (selection) => {
  personalAwardList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handlePublicationSelectionChange = (selection) => {
  publicationList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleReportSelectionChange = (selection) => {
  reportList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

const handleStudentAwardSelectionChange = (selection) => {
  studentAwardList.value.forEach((item) => {
    item.selected = selection.includes(item);
  });
};

// 获取历史记录数据
const fetchHistoryRecords = async () => {
  try {
    const response = await listMaterialHistory(currentPage.value, pageSize.value);
    console.log("response", response)
    if (response.code === 1) {
      historyRecords.value = response.data.records;
      total.value = response.data.total;
    } else {
      ElMessage.error('获取历史记录失败');
    }
  } catch (error) {
    console.error('获取历史记录出错:', error);
    ElMessage.error('获取历史记录失败');
  }
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchHistoryRecords();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchHistoryRecords();
};

// 处理下载操作
const handleDownload = (record) => {
  if (record.pdfUrl) {
    window.open(record.pdfUrl, '_blank');
  } else {
    ElMessage.warning('文件链接不存在');
  }
};

const handleCommand = async (command, record) => {
  switch (command) {
    case 'delete':
      ElMessageBox.confirm(
          '确定要删除这条记录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        try {
          const response = await deleteMaterialHistory(record.id);
          if (response.code === 1) {
            ElMessage.success('删除成功');
            fetchHistoryRecords(); // 刷新列表
          } else {
            ElMessage.error(`删除失败: ${response.msg}`);
          }
        } catch (error) {
          console.error('删除记录时出错:', error);
          ElMessage.error('删除失败，请稍后重试');
        }
      }).catch(() => {
        // 用户取消删除
      });
      break;

    case 'rename':
      ElMessageBox.prompt('请输入新的文件名', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: record.title, // 默认显示原始文件名
      }).then(async ({ value }) => {
        if (value !== record.title) { // 判断文件名是否修改
          try {
            const response = await updateMaterialHistoryTitle(record.id, value);
            if (response.code === 1) {
              ElMessage.success(`重命名成功：${value}`);
              fetchHistoryRecords(); // 刷新列表
            } else {
              ElMessage.error(`重命名失败: ${response.msg}`);
            }
          } catch (error) {
            console.error('重命名时出错:', error);
            ElMessage.error('重命名失败，请稍后重试');
          }
        }
      }).catch(() => {
        // 用户取消重命名
      });
      break;
  }
};

onMounted(() => {
  initCertificationData();
  initContinueEducationData();
  initSoftwareCopyrightData();
  initHorizontalData();
  initLongitudinalData();
  initOtherData();
  initPaperData();
  initPatentData();
  initPersonalAwardData();
  initPublicationData();
  initReportData();
  initStudentAwardData();
  fetchHistoryRecords();
})
</script>

<style scoped>
.container {
  color: #333;
  min-height: 100vh;
  /* 修改这里：从固定的左右边距改为水平居中 */
  margin: 2vh auto 0;
  max-width: 1200px;
  width: 80%;
}

.content-wrapper {
  background-color: white;
  display: flex;
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
  height: 60vh;
}

.sidebar-item {
  cursor: pointer;
}

.sidebar-item:hover {
  opacity: 1;
  background-color: rgba(0, 179, 138, 0.94);
  border: 1px solid rgba(0, 179, 138, 0.94);
  color: #fff;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40vh);
  position: relative;
}

.sidebar, .main-content, .history-section {
  /* background-color: transparent; */
}

.sidebar {
  width: 130px;
  border-right: 1px solid #ccc;
  padding: 20px;
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.hover-byover {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%
}
.hover-over {
  display: none;
  font-size: 14px;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.sidebar-item:hover .hover-byover {
  display: none;
}
.sidebar-item:hover .hover-over {
  display: flex;
}
.new-material {
  position: absolute;
  top: 0;
  width: 100%;
  height: calc(100% - 50px);
  flex: 1;
  border-bottom: 1px solid #ccc;
  padding: 100px;
  text-align: center;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.footer {
  position: absolute;
  bottom: 0;
  right: 10px;
  text-align: right;
  padding: 10px 0;
  flex-shrink: 0;
}

.item {
  width: 100%;
  height: 130px;
  cursor: pointer;
  border: 1px solid #ccc;
  margin-bottom: 10px;
  text-align: center;
  background-color: #F5F5F5;
}

.item:hover {
  background-color: #f0f0f0;
  border-color: #999;
}

.sidebar::-webkit-scrollbar {
  width: 6px;
  background-color: #1a1a1a;
}

.sidebar::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.sidebar::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.sidebar::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.history-table {
  background-color: white;
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.history-table th,
.history-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.history-table th {
  font-weight: 500;
  color: #666;
  background-color: #f8f8f8;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
  background-color: #ffd666;
}

.status-dot.completed {
  background-color: #52c41a;
}

.actions a {
  color: #1890ff;
  margin-right: 15px;
  cursor: pointer;
  text-decoration: none;
}

.actions a:hover {
  color: #40a9ff;
}
.file-filter {
  position: absolute;
  top: 0;
  width: 100%;
  height: calc(60vh - 50px);
  border-bottom: 1px solid #ccc;
}


/* 添加历史记录相关的样式 */
.history-section {
  margin-top: 20px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.history-title {
  padding: 20px;
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  border-bottom: 1px solid #eee;
}

.history-table-container {
  padding: 20px;
}

.history-table {
  width: 100%;
  border-collapse: collapse;
}

.history-table th,
.history-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.history-table th {
  font-weight: 500;
  color: #606266;
  background-color: #f5f7fa;
}

.status {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #67c23a;
}

.actions {
  display: flex;
  gap: 16px;
}

.actions a {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.actions a:hover {
  color: #66b1ff;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .history-table th:nth-child(2),
  .history-table td:nth-child(2) {
    display: none;
  }

  .actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
<style>
button:focus, button:focus-visible {
  outline: 0 auto -webkit-focus-ring-color;
}
</style>
